package cn.kuporo.seckill.order.application.listener;

import cn.hutool.core.util.StrUtil;
import cn.kuporo.seckill.common.constants.MQConstants;
import cn.kuporo.seckill.common.model.message.ErrorMessage;
import cn.kuporo.seckill.order.application.service.SeckillOrderService;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * @author: kuporo
 * @since: 2025/7/11
 * @description:  监听异常消息
 */
@Component
@RocketMQMessageListener(consumerGroup = MQConstants.TX_ORDER_CONSUMER_GROUP, topic = MQConstants.TOPIC_ERROR_MSG)
@RequiredArgsConstructor
@Slf4j
public class OrderErrorMessageListener implements RocketMQListener<String> {
    private final SeckillOrderService seckillOrderService;

    @Override
    public void onMessage(String message) {
        log.info("onMessage|秒杀订单微服务开始消费消息:{}", message);
        if (StrUtil.isEmpty(message)){
            return;
        }
        //删除数据库中对应的订单
        seckillOrderService.deleteOrder(this.getErrorMessage(message));
    }

    private ErrorMessage getErrorMessage(String msg){
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String txStr = jsonObject.getString(MQConstants.MSG_KEY);
        return JSONObject.parseObject(txStr, ErrorMessage.class);
    }
}
